#pragma once

#include <iostream>
#include <string>
#include <vector>
#include "InetAddr.hpp"

using namespace std;

class MessageRoute
{
private:
    bool Exist(const InetAddr &who)
    {
        for (auto iter = _online_user.begin(); iter != _online_user.end(); iter++)
        {
            if (*iter == who)
            {
                return true;
            }
        }
        return false;
    }

public:
    MessageRoute()
    {
    }
    void AddUser(const InetAddr &addr)
    {
        if (!Exist(addr))
            _online_user.push_back(addr);
        return;
    }
    void Route(int sockfd, const string message, const InetAddr who) // 转发消息
    {
        AddUser(who);
        if (message == "Quit" || message == "Q")
            DelUser(who);
        // 消息转发
        for (auto user : _online_user)
        {
            struct sockaddr_in tmp=user.addr();
            ::sendto(sockfd,message.c_str(),message.size(),0,(struct sockaddr*)&tmp,sizeof(tmp));
        }
    }
    void DelUser(const InetAddr &who)
    {
        for (auto iter = _online_user.begin(); iter != _online_user.end(); iter++)
        {
            if (*iter == who)
            {
                _online_user.erase(iter); // 用迭代器继续删除
                break;
            }
        }
    }
    ~MessageRoute()
    {
    }

private:
   std::vector<InetAddr> _online_user;
};
